﻿using System;
using System.ComponentModel;

using G.Runtime;
using G.Model;

namespace Minesweeper
{
    public class MyGameSpace : Component, HasGameSpace
    {
        private GameSpace _Game;
        
        public MyGameSpace()
        {
            GameSpaceDef def = new GameSpaceDef();
            def.Width = 9;
            def.Height = 9;
            MineSweeper.NumberOfBombs = 4;
            MineSweeper.Build(def);
            _Game = new GameSpace(def);
            
            _Game.Elements.Click += delegate(ElementEventArgs args)
            {
                args.element.Icon = "";
                if (args.element.Text == "B")
                {
                    GameEndEventArgs endErgs = new GameEndEventArgs();
                    endErgs.win = true;
                    _Game.FireEndEvent(endErgs);
                    ClearSquares();
                }
                else
                {
                    bool finished = true;
                    foreach (GameElement element in _Game.Elements)
                    {
                        if (element.Text != "B" && element.Icon != "")
                        {
                            finished = false;
                        }
                    }
                    
                    if (finished)
                    {
                        GameEndEventArgs endargs = new GameEndEventArgs();
                        _Game.FireEndEvent(endargs);
                        ClearSquares();
                    }
                    else
                    {
                        MineSweeper.RemoveSquares(_Game, args.element);
                    }
                }
            };
        }
        
        void ClearSquares()
        {
            foreach (GameElement element in _Game.Elements) {
                element.Icon = "";
            }
        }
        
        public GameSpace Game
        {
            get { return _Game; }
        }
    }
}
